import { ref, onMounted } from "vue";

//滚动效果
export function useScrollEle(elem) {
    const hoverIndex=ref(0);
    if(!elem) return;
    let flag = true;
    let flag2=false;
    let timer = null;
    function mouseenter() {
        flag = false;
    }
    function mouseleave() {
        flag = true;
    }
    function mouseenterChild(val){
        hoverIndex.value=val;
    }
    
    let cloneEle;
    function scrollRun() {
        flag=true;
        flag2=false;
        if(typeof elem === 'string'){
            elem = document.querySelector(elem);
        }
        if(!elem) return;
        if (elem.offsetHeight >= elem.firstElementChild.scrollHeight) return;
        let eleFirst = elem.firstElementChild;
        cloneEle = eleFirst.cloneNode(true);
        eleFirst.insertAdjacentElement("afterend", cloneEle);
        if(timer){
            clearInterval(timer);
            timer=null;
        }
        timer = setInterval(() => {
            if (!flag || flag2) return;
            elem.scrollTop += 2;
            if (elem.scrollTop >= eleFirst.scrollHeight) {
                flag2=false;
                elem.scrollTop = 0;
            }
        }, 100);
        if(cloneEle && cloneEle.children && cloneEle.children.length){
            for(let i=0;i<cloneEle.children.length;i++){
                cloneEle.children[i].addEventListener("mouseover",function(){
                    mouseenterChild(i)
                });
                cloneEle.children[i].addEventListener("mouseout",function(){
                    mouseenterChild(-1)
                });
            }
        }
        elem.addEventListener("mouseenter", mouseenter);
        elem.addEventListener("mouseleave", mouseleave);
    }
    onMounted(scrollRun);

    const resetScroll = () => {
        destroy();
        scrollRun();
    }
    const flagBool=(bool)=>{
        flag2=bool;
        if(!bool){
            hoverIndex.value=-1;
        }
    }
    const destroy = () => {
        if(typeof elem === 'string'){
            elem = document.querySelector(elem);
        }
        if(!elem) return;
        clearInterval(timer);
        timer=null;
        elem.removeEventListener("mouseenter", mouseenter);
        elem.removeEventListener("mouseleave", mouseleave);
        if(cloneEle && cloneEle.children && cloneEle.children.length){
            for(let i=0;i<cloneEle.children.length;i++){
                cloneEle.children[i].removeEventListener("mouseover", function(){
                    mouseenterChild(i)
                });
                cloneEle.children[i].removeEventListener("mouseout",function(){
                    mouseenterChild(-1)
                });
            }
        }
        cloneEle && cloneEle.remove();
        elem.scrollTop = 0;
        flag2=false;
    }
    return {
        resetScroll,
        destroy,
        hoverIndex,
        flagBool
    }
    //   let scrollBottom = elem.scrollHeight - elem.scrollTop - elem.clientHeight
}